<template>
  <CustomForm 
    :formData="formData"
    :columns="formColumns"
    @submit="submit"
    @reset="reset"
  />
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus/dist/index.full.js'
import { createGlobalConfig, editGlobalConfig } from '@/api'

const props = defineProps({
  id: {
    type: Number,
    default: null
  },
  configKey: String,
  configValue: String,
  description: String,
})
const emits = defineEmits(['close'])
const componentStatus = ref('create')
const formData = reactive({})

// 使用 computed 动态计算 formColumns，确保 disabled 属性响应式更新
const formColumns = computed(() => [
  {
    label: '配置键',
    prop: 'configKey',
    component: 'el-input',
    componentProps: {
      disabled: componentStatus.value === 'edit' // 直接绑定动态值
    }
  },
  {
    label: '配置值',
    prop: 'configValue',
    component: 'el-input',
  },
  {
    label: '配置描述',
    prop: 'description',
    component: 'el-input',
    componentProps: {
      type: 'textarea',
      autosize: {minRows: 3},
    },
    span: 24
  },
])

const submit = () => { 
  if(!props.id){
    createGlobalConfig(formData).then(res => {
      emits('close')
      ElMessage.success('新增成功')
    })
  } else {
    editGlobalConfig(formData).then(res => {
      emits('close')
      ElMessage.success('修改成功')
    })
  }
}

const reset = () => {
  emits('close')
}

onMounted(() => {
  if(!props.id) return
  componentStatus.value = 'edit'
  Object.assign(formData, props)
})
</script>